package org.shiro.demo.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
/**
 * @Author 一旦
 * @Time 2014-*-*
 */
@SuppressWarnings("unchecked")
public class JacksonUtils {
	private static ObjectMapper objectMapper = null;

	static {
		objectMapper = new ObjectMapper();
	}

	/*
	 * Write Object To Json
	 */

	public static String writeObject2Json(Object o)
			throws JsonGenerationException, JsonMappingException, IOException {
		return objectMapper.writeValueAsString(o);
	}

	public static String writeEntity2Json(Object o)
			throws JsonGenerationException, JsonMappingException, IOException {
		return objectMapper.writeValueAsString(o);
	}

	public static String writeMap2Json(Map<String, Object> map)
			throws JsonGenerationException, JsonMappingException, IOException {
		return objectMapper.writeValueAsString(map);
	}

	public static String writeList2Json(List<?> list)
			throws JsonGenerationException, JsonMappingException, IOException {
		return objectMapper.writeValueAsString(list);
	}

	/*
	 * Read Json To Object
	 */

	public static <T> T readJson2ObjectFromString(String jsonStr, Class<?> clazz)
			throws JsonParseException, JsonMappingException, IOException {
		return (T) objectMapper.readValue(jsonStr, clazz);
	}

	public static <T> T readJson2ObjectFromStream(InputStream inputStream,
			Class<?> clazz) throws JsonParseException, JsonMappingException,
			IOException {
		return (T) objectMapper.readValue(inputStream, clazz);
	}

	public static <T> T readJson2ObjectFromByteArray(byte[] bytes,
			Class<?> clazz) throws JsonParseException, JsonMappingException,
			IOException {
		return (T) objectMapper.readValue(bytes, 0, bytes.length, clazz);
	}

}
